$(document).ready(function(){
	refreshMyTable();
	getDefaultGroups();
//	alert("DD");
	
});
 
var json;
function getDefaultGroups()
{//(host);
	$.ajax({
	    url : host+'/easyskool/rest/idModService/getDefaultGroups',
		type : 'POST',
		data :'{}',
		dataType : 'json',
		contentType : "application/json; charset=utf-8",
		success : function(data,testStatus,jqXHR) {
			  json = jQuery.parseJSON(jqXHR.responseText);
			for(var i=0;i<json.length;i++)
		       $('#defaultGroupsTable').append('<tr><td><input name="groups'+i+'" type = "checkbox" value="'+json[i].agCode+'"/></td><td>'+json[i].agName+'</td><td>'+json[i].agDesc+'</td></tr>');
//					alert("Error: ! "+ jqXHR.responseText);
				 
		},
	error : function(data,testStatus,jqXHR) {
		alert("error occured");
		window.location = "http://localhost:8080/easyskool/Login/login.jsp";	
	}
    });
}

function saveCustomGroup()
{

	if($('#addGroupForm').valid()) {
		formData = ($('#addGroupForm').serializeArray());
		$.ajax({
		    url : host+'/easyskool/rest/idModService/saveCustomGroup',
			type : 'POST',
			data :converter(formData),
			dataType : 'json',
			contentType : "application/json; charset=utf-8",
			success : function(data,testStatus,jqXHR) {
				var json = jQuery.parseJSON(jqXHR.responseText);
					 alert(json.responseMessage);
			},
		error : function(data,testStatus,jqXHR) {
			var json = jQuery.parseJSON(jqXHR.responseText);
			alert(json.responseMessage+" ");
		}
	    });
    	}
}

function updateCustomGroup()
{

	if($('#updateForm').valid()) {
		formData = ($('#updateForm').serializeArray());
 alert( converter(formData));
		$.ajax({
		    url : host+'/easyskool/rest/idModService/updateCustomGroup',
			type : 'POST',
			data :converter(formData),
			dataType : 'json',
			contentType : "application/json; charset=utf-8",
			success : function(data,testStatus,jqXHR) {
				var json = jQuery.parseJSON(jqXHR.responseText);
					 alert(json.responseMessage);
			},
		error : function(data,testStatus,jqXHR) {
			var json = jQuery.parseJSON(jqXHR.responseText);
			alert(json.responseMessage+" ");
		}
	    });
    	}
}
var allCustomGroups;
function refreshMyTable()
{
	$.ajax({
		url:host+'/easyskool/rest/idModService/getCustomGroups',
		type:'POST',
		data: '{}',
		dataType: 'json',
		contentType: "application/json; charset=utf-8",
		success:function (data,testStatus,response) {
			var jsondata =JSON.parse(response.responseText);
			var toAppend = "";
			var hiddenCols = [""];
			allCustomGroups=jsondata;
			$("#mytable").remove();
			createMyTable();
			
			$("#mytable").append("<tbody id='tbodyId'>");
			$.each(jsondata, function(i, item) {
				toAppend = "";
				toAppend = startTableRow(toAppend, i);
				toAppend = addCheckboxToTableRow(toAppend, 'checkboxselect', i);
				toAppend = jsonItemToString(toAppend, item, hiddenCols);
				toAppend = addButtonWithModalToTable(toAppend, 'Update', 'btn btn-info', 'update', 'myUpdateModal',jsondata[i].agCode);
				toAppend = addButtonWithoutModalToTable(toAppend, 'Delete', 'btn btn-danger', 'remove');
				toAppend = endTableRow(toAppend);
				$("#mytable").append(toAppend);
			});
			$("#mytable").append("</tbody>");
		},
			error:function (data,testStatus,response) {
			alert("Error fetching data");
			}
	});
	
	attachClickEventToUpdateButton();
	attachClickEventToDeleteButton();
	attachClickEventToSelectAllCheckBox();
}

function addButtonWithModalToTable(toAppend, buttonValue, buttonClass,
		buttonId, modalName,code) {
	toAppend = toAppend + "<td><input type='button' value='" + buttonValue
			+ "' class='" + buttonClass + "' id='" + buttonId
			+ "' data-toggle='modal' data-target='#" + modalName + "' name='"+code+"' onclick='getdefaultGroupsforCustomGroup(this.name);' /></td>";
	return toAppend;
}
function attachClickEventToUpdateButton() {
	$('#mytable').on('click', '#update', function(){
    	tableRowToModalForm($(this).closest('tr'),'u','updateForm');
   });
}

function jsonItemToString(toAppend, item, hiddenCols) {

	$.each(item, function(key, value) {
		var found = $.inArray(key, hiddenCols) > -1;
		if (found == false) {
			toAppend = toAppend + "<td class='" + key + "'>" + value + "</td>";
		} else {
			toAppend = toAppend + "<td class='" + key + "' hidden='true'>"
					+ value + "</td>";
		}

		// alert(key + "," + value);
	});

	return toAppend;
}

function getdefaultGroupsforCustomGroup(code)
{
	$.ajax({
	    url : host+'/easyskool/rest/idModService/getCustomGroup',
		type : 'POST',
		data :'{"agCode":"'+code+'"}',
		dataType : 'json',
		contentType : "application/json; charset=utf-8",
		success : function(data,testStatus,jqXHR) {
			var jsonSingle = jQuery.parseJSON(jqXHR.responseText);
//			var rows = document.getElementById('defaultGroupsTableUpdate').rows.length;
			$("#defaultGroupsTableUpdate tr").remove();
//			for(var i=0;i<rows;i++)
			for(var i=0;i<json.length;i++)
			       $('#defaultGroupsTableUpdate').append('<tr><td><input name="groupNames'+i+'" type = "checkbox" id="'+json[i].agCode+'" value="'+json[i].agCode+'"/></td><td>'+json[i].agName+'</td><td>'+json[i].agDesc+'</td></tr>');
			for(var i=0;i<allCustomGroups.length;i++)
				if(allCustomGroups[i].agCode==code)
					{
					document.getElementById("ugroupName").value=allCustomGroups[i].agName;
					document.getElementById("udescription").value=allCustomGroups[i].agDesc;
					document.getElementById("ucode").value=allCustomGroups[i].agCode;
					
					}
		
			for(var i=0;i<jsonSingle.length;i++)
				{
				document.getElementById(jsonSingle[i].agCode).checked=true;
				}
		},
	error : function(data,testStatus,jqXHR) {
		var json = jQuery.parseJSON(jqXHR.responseText);
		alert(json.responseMessage+" ");
	}
    });
}

function attachClickEventToDeleteButton() {
	$('#mytable').on('click', '#remove', function(){
    	
    	var curRowId = $(this).closest('tr');
    	alert(curRowId.children('td.agCode').text()+"Irytjt");
    	$("#myConfirmModal").modal('show');
    	
    	$('#confirmDelete').click(function() {
    		$("#myConfirmModal").modal('hide');
           	$.ajax({
           		url : host+'/easyskool/rest/idModService/deleteCustomGroup',
       			type : 'POST',
       			data : '{"agCode":"'+curRowId.children('td.agCode').text()+'"}',
       			dataType : 'json',
       			async : false,
       			contentType : "application/json; charset=utf-8",
       			success : function(data,testStatus,response) {
       				var json = jQuery.parseJSON(response.responseText);
       				if(json.del == "success"){
       					refreshMyTable();
       				} else	{
       					$("#ErrorContent").html(json.del);
    					$("#myErrorModal").modal('show');
       				}
       			}
           	});
//           	
            
        });
    	
    	$('#cancelDelete').click(function() {
    		$("#myConfirmModal").modal('hide');
    	
    	});
    	
    });
}

function createMyTable() {
	var toAppend = "";
	//var tableId = "mytable";
	var theaders = ["Group Name ",
	                "Group Description"
	               ];
	toAppend +=	"<table class='table form-fields table-striped tablesorter' id='mytable'>";
	toAppend = createTableHeader(toAppend, theaders, true);
	toAppend = attachPaginationBarToTable(toAppend);
	toAppend += "</table>";
	
	$("#tableDiv").append(toAppend);
}

function attachClickEventToSelectAllCheckBox() {
	$('.form-fields').on('click', '#chkall', function(){
		if(this.checked)
			{
				$('input[name=checkboxselect]').prop('checked', true);
			} else {
				$('input[name=checkboxselect]').prop('checked', false);
			}
	});
}
